package com.hzj.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzj.pojo.BolgComment;
import com.hzj.pojo.BolgDatail;
import com.hzj.pojo.User;
import com.hzj.service.BolgCommentService;
import com.hzj.service.BolgDatailService;
import com.hzj.service.UserService;
import com.hzj.utils.Encryption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hzj
 * @since 2021-04-22
 */
@RestController

public class UserController {
    @Autowired
    UserService us;
    @Autowired
    BolgDatailService bds;
    @Autowired
    BolgCommentService bcs;

    @RequestMapping("/test")
    public String test() {
        //        int i = 1 / 0;
        System.out.println("测试");
        return "我是8002";
    }

    @RequestMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userName", username);
        wrapper.eq("password", Encryption.createPassword(password));
        HttpSession session = request.getSession();
        User user = us.getOne(wrapper);
        if (user != null) {
            session.setAttribute("UserToken", user);
            return "成功";
        }

        return "登录失败";
    }

    @RequestMapping("/showAll")
    public List<BolgDatail> showAll() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.orderByDesc("createDate");
        List<BolgDatail> list = bds.list(wrapper);
        return list;
    }

    @RequestMapping("/add")
    public String add(@RequestBody BolgComment bolgComment, HttpSession session) {
        System.err.println(bolgComment);
        User userToken = (User) session.getAttribute("UserToken");
        bolgComment.setCreateuser(1l);
        boolean save = bcs.save(bolgComment);
        if (save) {
            return "添加成功";
        }
        return "添加失败";
    }

    @RequestMapping("/session")
    public String session(HttpSession session) {
        session.setAttribute("user", "sb");
        System.out.println("id:" + session.getId() + "值：" + session.getAttribute("user"));

        return "存取成功";
    }
    @RequestMapping("/session1")
    public String session1(HttpSession session) {
        System.out.println("id:" + session.getId() + "值：" + session.getAttribute("user"));
        return session.getAttribute("user")==null?"空值":session.getAttribute("user").toString();
    }
}

